package com.topscomm.center.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.web.multipart.MultipartFile;

import com.topscomm.center.pojo.FileManageEntity;
import com.topscomm.file.FileInfoDTO;

public class FileCenterUtil {
	/**
	 * 
	 * @description:
	 * @param file
	 * @return
	 * @throws Exception
	 * @author: donghang
	 * @date: 2021年4月9日下午12:40:41
	 * @modify:
	 */
	public static File multipartFileToFile(MultipartFile file) throws Exception {
		File toFile = null;
		if (file == null || file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		return toFile;
	}

	/**
	 * 文件实体转文件服务实体
	 * 
	 * @description:
	 * @param file
	 * @return
	 * @throws Exception
	 * @author: donghang
	 * @date: 2021年4月9日下午12:42:14
	 * @modify:
	 */
	public static FileInfoDTO fileEntityConvertToFileServiceDto(FileManageEntity fileManageEntity) {
		FileInfoDTO fileInfo = new FileInfoDTO();
		fileInfo.setStorageType(fileManageEntity.getStoragetype());
		fileInfo.setBucketName(fileManageEntity.getBucketname());
		fileInfo.setFileDirPath(fileManageEntity.getDirpath());
		fileInfo.setFileId(fileManageEntity.getIdentifier());
		fileInfo.setFileName(fileManageEntity.getLocation());
		return fileInfo;
	}

	/**
	 * 文件实体转文件服务实体,使用转换的文件名称
	 * 
	 * @description:
	 * @param file
	 * @return
	 * @throws Exception
	 * @author: donghang
	 * @date: 2021年4月9日下午12:42:14
	 * @modify:
	 */
	public static FileInfoDTO fileEntityConvertToFileServiceDto(FileManageEntity fileManageEntity,
			String convertFilename) {
		FileInfoDTO fileInfo = new FileInfoDTO();
		fileInfo.setStorageType(fileManageEntity.getStoragetype());
		fileInfo.setBucketName(fileManageEntity.getBucketname());
		fileInfo.setFileDirPath(fileManageEntity.getDirpath());
		fileInfo.setFileId(fileManageEntity.getIdentifier());
		fileInfo.setFileName(convertFilename);
		return fileInfo;
	}

	/**
	 * 
	 * @description:
	 * @param ins
	 * @param file
	 * @author: donghang
	 * @date: 2021年3月31日下午6:31:55
	 * @modify:
	 */
	// 获取流文件
	private static void inputStreamToFile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
